class Page{
    constructor(ops){
        // 接收参数，处理参数
        this.length = ops.length;
        this.num = ops.num || 2;
        this.prev = ops.prev;
        this.next = ops.next;
        this.pageList = ops.pageList;
        this.index = ops.index || 0;
        this.data = ops.data;
        this.cont = ops.cont;
        // 创建页码
        this.createPage();
        this.addEvent();
        this.display();
    }
    createPage(){
        this.max = Math.ceil(this.length/this.num);
        let str = "";
        for(let i=0;i<this.max;i++){
            str += `<li>${i+1}</li>`;
        }
        this.pageList.innerHTML = str;

        this.li = this.pageList.children;
        this.setActive();
    }
    setActive(){
        // console.log(this.li);
        for(let i=0;i<this.li.length;i++){
            this.li[i].style.background = "";
            this.li[i].style.color = "";
        }
        this.li[this.index].style.color = "#fff";
        this.li[this.index].style.background = "#ff464e";
    }
    addEvent(){
        var that = this;
        this.prev.onclick = function(){
            if(that.index == 0){
                that.index = 0;
            }else{
                that.index--;
            }
            that.setActive();
            that.display();
        }
        this.next.onclick = function(){
            if(that.index == that.max-1){
                that.index = that.max-1;
            }else{
                that.index++;
            }
            that.setActive();
            that.display();
        }
    }
    display(){
        var str = "";

        // 分页的核心：公式
        // this.index     this.num
        // 1: this.index0*this.num3  ~  (this.index0+1)*this.num3
        // 2: this.index1*this.num3  ~  (this.index1+1)*this.num3
        // 3: this.index2*this.num3  ~  (this.index2+1)*this.num3
        // 4: this.index3*this.num3  ~  (this.index3+1)*this.num3

        for(var i=this.index*this.num; i<(this.index+1)*this.num; i++){
            if(i<this.data.length){
                str += `<li index = "${this.data[i].goodsId}">
                        <a href="page/Detail.html?id=${this.data[i].goodsId}">
                        <img src="${this.data[i].img.largeImg[0]}">
                        <span>￥${this.data[i].span}</span>
                        <s>${this.data[i].s}</s>
                        <p>${this.data[i].p}<em>${this.data[i].em}</em></p>
                        </a>
                    </li>`
            }
        }
        this.cont.innerHTML = str;
    }
}

